package com.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class ComsumerProxy {

    public static <T> T getProxy(final Class<T> interfaceClass, final String host, final int port){

            return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass},
                new ConsumerHandler(host, port));
    }
}

class ConsumerHandler implements InvocationHandler{
    private String host;
    private int port;

    public ConsumerHandler(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        try {
            Socket socket = new Socket(host, port);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest request = new RpcRequest(method.getDeclaringClass().getName(), method.getName(),
                    method.getParameterTypes(), args);
            outputStream.writeObject(request);
            Object result = inputStream.readObject();
            return  result;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
